package com.mhy.ssm.service.impl;

import com.mhy.ssm.mapper.AccountMapper;
import com.mhy.ssm.pojo.Account;
import com.mhy.ssm.service.AccountService;
import com.mhy.ssm.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountMapper accountMapper;

    @Autowired
    LogService logService;

    @Override
    public void save(Account account) {
        accountMapper.save(account);
    }

    @Override
    public void update(Account account){
        accountMapper.update(account);
    }

    @Override
    public void delete(Integer id) {
        accountMapper.delete(id);
    }

    @Override
    public Account findById(Integer id) {
        return accountMapper.findById(id);
    }

    @Override
    public List<Account> findAll() {
        return accountMapper.findAll();
    }


    @Override
    public Boolean transfer (String from, String to, Double money) {
        boolean flag = true;

        try {
            Account fromAcc = accountMapper.findByName(from);
            Account toAcc = accountMapper.findByName(to);
            if(fromAcc.getMoney()>=money){
                fromAcc.setMoney(fromAcc.getMoney() - money);
                accountMapper.update(fromAcc);
                toAcc.setMoney(toAcc.getMoney() + money);
                accountMapper.update(toAcc);
            } else {
                System.out.println("Transfer false");
                flag = false;
                throw new RuntimeException("转账失败");
            }
        } finally {

            logService.save(from, to, money, flag);
        }


        return true;
    }
}